Lambda Expressions

Lambda expressions allow us to create "anonymous" functions i.e functions without a name. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.

Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs.

However the following are the key differences between lambda functions and 'def' functions.

  1. Lambda's body is a single expression, not a block of statements
  2. 'Lambda' is designed for coding simple functions and 'def' handles the larger tasks.

In [2]:
# Normal function

def square(num):
    result = num**2
    return result

square(2)


Out[2]:
4

In [3]:
# Simplified Version #1
def square(num):
    return num**2

square(3)


Out[3]:
9

In [4]:
# Simplified Version #1
def square(num):return num**2

square(4)


Out[4]:
16

The syntax for lambda function is quite simple.

lambda argument_list:expression

The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments.

The following example returns the square of a given number.


In [5]:
square = lambda num: num **2
square(5)


Out[5]:
25

In [7]:
sum1 = lambda x,y: x+y
print(sum1(3,4))
even = lambda x: x%2==0
print(even(12))
first = lambda str: str[0]
print(first('Hello'))
rev = lambda str:str[::-1]
print(rev('Hello'))


7
True
H
olleH

Filter Function

The function filter(function,list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.

The function filter(f,1) needs a function f as its first argument. f returns a Boolean value i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list included in the resultset.


In [13]:
nums = [2,3,4,7,9,10]
evens = list(filter(lambda x: x%2==0,nums))
print(evens)


[2, 4, 10]

Map Function

map is a function with 2 arguments.

result = map(function,seq)

The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq.

It returns a new list with all the elements changed by func.


In [22]:
def far(T):
    return ((float(9)/5)* T + 32)
def cel(T):
    return (float(5)/9) * (T - 32)

temp = (0,35,90,125)
F = map(far,temp)
temp1 = list(F)
C = map(cel,temp1)
print(temp1)
print(list(C))


[32.0, 95.0, 194.0, 257.0]
[0.0, 35.0, 90.0, 125.0]

In [26]:
temp = (0,35,90,125)
f = map(lambda x: (float(9)/5)*x +32,temp)
f_list = list(f)
c = map(lambda x: (float(5)/9) * (x -32),f_list)
print(f_list)
print(list(c))


[32.0, 95.0, 194.0, 257.0]
[0.0, 35.0, 90.0, 125.0]

map() can also be applied to more than one list but the lists must have the same length. map() will apply its lambda function to the elements of the argument lists, i.e. it first applies to the elements with the 0th index, then to the elements with the 1st index until the n-th index is reached:


In [30]:
a = [1,2,3,4]
b = [5,6,7,8]
c = [-1,-2,1,2]

list(map(lambda x,y,z:x+y-z,a,b,c))


Out[30]:
[7, 10, 9, 10]

Reduce Function

reduce(func,seq)

If seq = [s1,s2,s3,...,sn], calling reduce(func,seq) works like this:

  • At first the two elements of seq will be applied to func, i,e func(s1,s2). The list on which reduce() works looks now like this: [func(s1,s2),s3,...,sn]
  • In the next step func will be applied on the previous result and the third element on the list, i.e.func(func(s1,s2),s3). The list looks like this now: [func(func(s1,s2),s3),...,sn]
  • Continue like this until just one element is left and return this element as the result of reduce()

In [34]:
from functools import reduce
reduce(lambda x,y: x+y, [47,23,11,34])


Out[34]:
115

In [35]:
from functools import reduce
reduce(lambda x,y: x if (x > y) else y, [47,12,33,95])


Out[35]:
95

In [39]:
from functools import reduce
reduce(lambda x,y: x * y, range(1,10,2))


Out[39]:
945

Zip Function

zip() makes an iterator that aggregates elements from each of the iterables.


In [41]:
a = [1,2,3]
b = [4,5,6]

list(zip(a,b))


Out[41]:
[(1, 4), (2, 5), (3, 6)]

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. Only the shortest iterable itme will be taken and any extra elements will be ignored


In [42]:
# Example - 1
x = [1,2,3]
y = [4,5]

list(zip(x,y))


Out[42]:
[(1, 4), (2, 5)]

In [43]:
# Example - 2
a = ['a','b']
b = ['c','d','e']

list(zip(a,b))


Out[43]:
[('a', 'c'), ('b', 'd')]

Zip with Dictionary


In [47]:
d1 = {'a':1,'b':2}
d2 = {'c':3,'c':4}
print(list(zip(d1,d2)))


[('a', 'c')]

This makes sense because simply iterating through the dictionaries will result in just the keys. We would have to call methods to mix keys and values


In [50]:
def swapdic(d1,d2):
    dout = {}
    
    for d1key,d2val in zip(d1,d2.values()):
        dout[d1key] = d2val
    
    return dout

swapdic(d1,d2)


Out[50]:
{'a': 4}

Enumerate Function

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. Returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.


In [53]:
colors = ['Blue','Black','White','Red']
list(enumerate(colors))


Out[53]:
[(0, 'Blue'), (1, 'Black'), (2, 'White'), (3, 'Red')]

In [54]:
list(enumerate(colors,1))


Out[54]:
[(1, 'Blue'), (2, 'Black'), (3, 'White'), (4, 'Red')]

In [56]:
for index,item in enumerate(colors):
    print(index)
    print(item)


0
Blue
1
Black
2
White
3
Red

In [57]:
for i,j in enumerate(colors):
    if i == 2:
        break
    print(j)


Blue
Black

Any / All


In [58]:
lst = [True, True, False, True]
all(lst)


Out[58]:
False

In [59]:
any(lst)


Out[59]:
True

Complex

complex() returns a complex number with the value real + imag*1j or converts a string or number to a complex number.


In [1]:
complex()  # if no arguments are given results in 0j


Out[1]:
0j

In [4]:
complex(2,4)


Out[4]:
(2+4j)

In [2]:
complex('2') # if imag part is omitted substitutes with 0j


Out[2]:
(2+0j)

In [5]:
complex('2','3') # this will create an error as the second parameter cannot be a string.


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-1ed7d50de2f3> in <module>()
----> 1 complex('2','3')

TypeError: complex() can't take second arg if first is a string

In [3]:
complex('1+2j')


Out[3]:
(1+2j)

In [8]:
complex('3',2)  # cannot take a secord argument if first is a strink


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-206b650f1f6e> in <module>()
----> 1 complex('3',2)  # cannot take a secord argument if first is a strink

TypeError: complex() can't take second arg if first is a string